package com.huanglejing.shanggou.fragment

import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.activity.ProductDetailActivity
import com.huanglejing.shanggou.activity.SaveOrderActivity
import com.huanglejing.shanggou.adapter.NowOrderAdapter
import com.huanglejing.shanggou.bean.CompanyListBean
import com.huanglejing.shanggou.common.AppBaseFragment
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.data.*
import com.huanglejing.shanggou.greendao.CacheGoodsBean
import com.huanglejing.shanggou.greendao.CacheGoodsBeanDao
import com.huanglejing.shanggou.greendao.CacheOrderBean
import com.huanglejing.shanggou.greendao.CacheOrderBeanDao
import com.huanglejing.shanggou.interfaces.IonSlidingViewClickListener
import com.huanglejing.shanggou.interfaces.NowOrderContract.NowOrderPresenter
import com.huanglejing.shanggou.interfaces.NowOrderContract.NowOrderView
import com.huanglejing.shanggou.presenterimpl.NowOrderImpl
import com.huanglejing.shanggou.utils.UIHelper
import com.huanglejing.shanggou.utils.checkEmpty
import com.huanglejing.shanggou.utils.formatNum
import com.huanglejing.shanggou.view.EmptyLayout
import com.rtdl.dropdownmenu.NormalMenuHolder
import kotlinx.android.synthetic.main.activity_new_com_pro.*
import kotlinx.android.synthetic.main.fragment_now_order.*

/**
 * Created by Administrator on 2016/8/5 0005.
 */
class NowOrderFragment : AppBaseFragment<NowOrderPresenter<NowOrderView>, NowOrderView>(),
        NowOrderView, IonSlidingViewClickListener {
    protected var mRv: RecyclerView? = null
    protected var mEmptyLayout: EmptyLayout? = null
    var mData = arrayListOf<CacheGoodsBean>()
    var companyId = ""
    var allPrice = 0.00
    var leftPosition = 0
    var myAdapter: NowOrderAdapter? = null
    val menusData = arrayListOf<CompanyListBean>()
    var llContainer: LinearLayout? = null

    private var loadAll: List<CacheGoodsBean>? = null
    private val menu by lazy {
        NormalMenuHolder(activity, getAllPrice()) { view, i ->
            leftPosition = i
            allPrice = getAllPrice()?.getOrNull(i)?.toDoubleOrNull()?:0.00
            companyId = menusData?.getOrNull(i)?.companyId?.toString() ?: ""
            loadAll = getCacheGoods()
            showContent(loadAll)
            //   myAdapter?.notifyDataSetChanged()
        }
    }

//    override fun getCompanyListParams(): Observable<Map<String, Any>> {
//        val map = ArrayMap<String, String>().apply {
//            put("customerId", CacheCustomerId ?: "")
//        }
//        return Observable.just(map)
//    }

    override fun showCompanyList(data: ArrayList<CompanyListBean>) {
        if (data.checkEmpty()) {
            return
        }
        menusData?.clear()
        menusData?.addAll(data)

        data?.forEachIndexed { index, companyListBean ->
            if (companyListBean?.companyId?.equals(companyId)?:false){
                leftPosition=index
            }
        }
        llContainer?.removeAllViews()
        llContainer?.addView(menu.dropMenu)
        menu.isAutoRefresh = false
        menu.setMenuListData((data?.map { it?.companyDisplayName ?: "" } as? ArrayList)
                ?: arrayListOf<String>())
        menu?.outsideMenuClick(leftPosition, 0)
        allPrice= getAllPrice()?.get(leftPosition)?.toDoubleOrNull()?:0.00
        //    mBasePresenter?.getNowOrder()
    }


    init {
        containerId = R.id.fl_head_container
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }


    override fun createPresenter(): Any? = NowOrderImpl()

    override fun getLayoutId(): Int = R.layout.fragment_now_order

    override fun initWidget(rootView: View?) {

        llContainer = rootView?.findViewById<LinearLayout>(R.id.ll_now_order_container)
        mRv = view?.findViewById(R.id.simple_recycle_view)
        val manager = LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)
        mRv?.layoutManager = manager

        myAdapter = NowOrderAdapter()

        myAdapter?.setIonSlidingViewClickListener(this@NowOrderFragment)
        mRv?.adapter = myAdapter

        loadComplete(true)
        tv_save_order?.setOnClickListener {
            if (allPrice <= 0.0) {
                return@setOnClickListener
            }
            val mNetData = loadAll?.filter {
                it?.companyId?.equals(companyId) ?: false
            } ?: emptyList()
            val goods = StringBuffer()
            if (mNetData != null) {
                mNetData?.forEachIndexed { index, cacheGoodsBean ->
                    goods.append(cacheGoodsBean.id).append("#")
                }
            }
            var allOrder = getCacheOrders()?.filter {
                it.companyId?.equals(companyId) ?: false
            }
            var isHasOrder = false
            var orderBean: CacheOrderBean? = null
            allOrder?.forEachIndexed { index, cacheOrderBean ->
                if (companyId.equals(cacheOrderBean.companyId)) {
                    isHasOrder = true
                    orderBean = cacheOrderBean
                }

            }
            if (isHasOrder && orderBean != null) {
                orderBean?.goods = goods?.toString() ?: ""
                orderDao?.update(orderBean)
                val bun = Bundle()
                bun?.putSerializable("companyId", companyId)
                UIHelper.startActivity(SaveOrderActivity::class.java, bun)
            } else if (!isHasOrder && orderBean == null) {
                orderBean = CacheOrderBean()
                orderBean?.companyId = companyId
                orderBean?.customerId = CacheCustomerId ?: ""
                orderBean?.bz = ""
                orderBean?.goods = goods?.toString() ?: ""
                orderDao?.insert(orderBean)
                val bun = Bundle()
                bun?.putSerializable("companyId", companyId)
                UIHelper.startActivity(SaveOrderActivity::class.java, bun)
            }

        }

    }


    override fun onItemClick(view: View?, position: Int) {
        (mData?.get(position) as? CacheGoodsBean)?.let {
            val bun = Bundle()
            bun.putLong("id", it?.id)
            UIHelper.startActivity(ProductDetailActivity::class.java, bun)
        }
    }

    override fun onDeleteBtnCilck(view: View?, position: Int) {
        val deleteBean = mData?.get(position) as? CacheGoodsBean
        beanDao?.delete(deleteBean)
        loadAll = getCacheGoods()?.filter {
            it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
        }
        showContent(loadAll)
    }

    override fun onSetBtnCilck(view: View?, position: Int) {
    }

    override fun onResume() {
        super.onResume()
        setIvExitVisible(false)
        setIvExitShow()
        showCompanyList(getCacheCompanyList() ?: arrayListOf())
        if (getActivity()?.findViewById<ViewPager>(R.id.main_container)?.currentItem == 2) {
            getActivity()?.findViewById<TextView>(R.id.tv_title)?.setText(resources.getString(R.string.str_current_order))
            getActivity()?.findViewById<TextView>(R.id.tv_login_language)?.visibility = View.GONE
        }

    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        if (isVisibleToUser) {
            setIvExitVisible(false)
            getActivity()?.findViewById<TextView>(R.id.tv_title)?.setText(resources.getString(R.string.str_current_order))
            companyId = AppContext.get().companyId ?: ""
            showCompanyList(getCacheCompanyList() ?: arrayListOf())
        } else {
        }
        super.setUserVisibleHint(isVisibleToUser)

    }

    override fun <T> showContent(data: T?) {
        try {
            menu?.setDataPrice(getAllPrice())
            val mNetData = (data as? List<CacheGoodsBean>)?.filter {
                it?.companyId?.equals(companyId) ?: false
            } ?: emptyList()
            if (mNetData != null) {
                mData?.clear()
                mData?.addAll(mNetData)
                allPrice = getAllPrice()?.get(leftPosition)?.toDoubleOrNull() ?: 0.00
                tv_now_order_total?.setText("${resources.getString(R.string.str_total)}${formatNum(allPrice)}€")
//                if (allPrice > 100) {
//                    tv_save_order?.setText(resources.getString(R.string.str_save_order))
//                    tv_save_order?.isClickable = true
//                    tv_save_order?.isEnabled = true
//                    tv_save_order?.setBackgroundColor(Color.parseColor("#367BB9"))
//                    tv_save_order?.setTextColor(Color.WHITE)
//                } else {
//                    tv_save_order?.setText("${resources.getString(R.string.str_lack)}${formatNum(100.minus(allPrice))}")
//                    tv_save_order?.isClickable = false
//                    tv_save_order?.isEnabled = false
//                    tv_save_order?.setBackgroundColor(Color.parseColor("#777777"))
//                    tv_save_order?.setTextColor(Color.WHITE)
//                }
                myAdapter?.setNewData(mData ?: arrayListOf())
                //   myAdapter?.notifyDataSetChanged()
            } else {
                tv_now_order_total?.setText("${resources.getString(R.string.str_total)}${formatNum(allPrice)}€")
//                tv_save_order?.setText("${resources.getString(R.string.str_lack)}${formatNum(100.minus(allPrice))}")
//                tv_save_order?.isClickable = false
//                tv_save_order?.isEnabled = false
//                tv_save_order?.setBackgroundColor(Color.parseColor("#777777"))
//                tv_save_order?.setTextColor(Color.WHITE)
            }
            loadComplete(true)
        } catch (e: Exception) {
            KLog.e(e?.message)
        }

    }

    fun loadComplete(end: Boolean = false) {
        this.mEmptyLayout = EmptyLayout.getEmptyLayout(EmptyLayout.NODATA, mRv)
        myAdapter?.setHeaderAndEmpty(myAdapter?.headerLayoutCount ?: 0 > 0)
        //  mRv?.post {
        myAdapter?.loadMoreComplete()
        if (end) {
            myAdapter?.loadMoreEnd()
            if (myAdapter?.data?.size ?: 0 <= 0) {
                mEmptyLayout?.setErrorType(EmptyLayout.NODATA)
                myAdapter?.setEmptyView(mEmptyLayout)
            } else {
                mEmptyLayout?.setErrorType(EmptyLayout.COMPLETE)
                val foot = EmptyLayout.getEmptyLayout(EmptyLayout.COMPLETE, mRv)
                myAdapter?.removeAllFooterView()
                myAdapter?.setFooterView(foot)
            }
        }
        //   }
    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
        myAdapter?.setNewData(arrayListOf())
        myAdapter?.setHeaderAndEmpty(myAdapter?.headerLayoutCount ?: 0 > 0)
        xr_toolbar_list.post {
            myAdapter?.loadMoreComplete()
            myAdapter?.loadMoreEnd()
            mEmptyLayout?.setErrorType(EmptyLayout.NETWORK_ERROR)
            mEmptyLayout?.setOnLayoutClickListener {
                //  mBasePresenter?.getNewComProList()
            }
            myAdapter?.setEmptyView(mEmptyLayout)
        }
    }

    override fun initData() {

    }

    companion object {
        @JvmStatic
        fun newInstance(): NowOrderFragment {
            return NowOrderFragment()
        }
    }

}